package com.linchaoen.elema.service.impl;

import com.linchaoen.elema.config.CacheKeyManager;
import com.linchaoen.elema.mapper.FoodMapper;
import com.linchaoen.elema.mapper.OrderMapper;
import com.linchaoen.elema.mapper.UserMapper;
import com.linchaoen.elema.model.entity.Food;
import com.linchaoen.elema.model.entity.Order;
import com.linchaoen.elema.model.entity.Store;
import com.linchaoen.elema.model.entity.User;
import com.linchaoen.elema.service.OrderService;
import com.linchaoen.elema.service.UserService;
import com.linchaoen.elema.utils.BaseCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private BaseCache baseCache;

    @Override
    @Transactional
    public int saveOrder(Integer uid, Integer fid, Integer num) {

        User user = userMapper.findUserById(uid);
        Food food = foodMapper.findFoodById(fid);
        Store store = foodMapper.findStoreByFoodId(fid);

        if (user != null && food != null && store != null) {
            Order order = new Order();
            order.setUserId(uid);
            order.setStoreId(store.getId());
            order.setFoodId(food.getId());
            order.setOrderStoreName(store.getStoreName());
            order.setOrderFoodName(food.getFoodName());
            order.setUserName(user.getName());
            order.setIsComplete("1");
            order.setCreateTime(new Date());
            order.setNum(num);
            order.setPrice(num * food.getPrice());
            order.setStoreImg(store.getCoverImg());
            order.setFoodImg(food.getFoodImg());
            int rows = orderMapper.saveOrder(order);
            return rows;
        } else {
            return -1;
        }

    }

    @Override
    public List<Order> findOrderByUid(int uid) {
        List<Order> orderList = orderMapper.findOrderByUid(uid);
        return orderList;
    }

}
